package com.example.mobile2032021606170hsy0618;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;//声明数据库变量
    private SQLiteDatabase database;//声明数据库对象变量

    public void openDB(Context context) {
        //创建数据库助手对象
        openHelper = new MySQLiteOpenHelper(context, "student.db", null, 1);

        try {
            database = openHelper.getWritableDatabase();
        } catch (Exception e) {
            database = openHelper.getReadableDatabase();
        }
    }

    public void closeDB() {
        if (database != null) {
            database.close();
            ;
            database = null;
        }
        if (openHelper != null) {
            openHelper.close();
            openHelper = null;
        }
    }
//查询所有数据
    public List<Users> QueryAll(Context context){
        List<Users> usersList=new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("users", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                float score = cursor.getInt(3);
                usersList.add(new Users(id, name, age, score));
            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return  usersList;
    }
    //添加数据
    public  long insert(Context context,Users user){
        openDB(context);
        ContentValues values = new ContentValues();//定义键值对数据
        values.put("name",user.getName());//设计数据
        values.put("age",user.getAge());
        values.put("score",user.getScore());
       long result = database.insert("users",null,values);
       closeDB();
       return result;
}
//数据ID删除数据
public  int delete(Context context,int id){
    openDB(context);//打开数据库
    int result=database.delete("users","_id=?",new String[]{String.valueOf(id)});
    closeDB();//关闭数据库
    return  result;
}
//数据ID更新数据
public  int updata(Context context,int id,Users user){
    openDB(context);
    ContentValues values=new ContentValues();
    values.put("name",user.getName());
    values.put("age",user.getAge());
    values.put("score",user.getScore());
    int result=database.update("users",values,"_id=?",new String[]{String.valueOf(id)});
    closeDB();
    return result;
}

}
